package nautilus.placetaker.dao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MoneyDataHelper  extends SQLiteOpenHelper{

	private static final int DATABASE_VERSION = 1;
	private static String DBFILE = "dbcreate.sql";
	private static String DB_NAME = "PLACETRACKER_DB";
	
	public static String PLACE_TABLE = "Places";
	public static final String[] columns_account = {"_id","_name", "_address", 
		"_latitude", "_longitude","_image1","_image2","_image3","_image4", 
		"_categoryId", "_categoryName","_description", "_audio","_lastUpdate","_isChecked"};
	
	public static String CATEGORY_TABLE = "PlaceCategory";
	public static final String[] columns_category = {"_id","_name"};
	
	private Context _context;
	
	public MoneyDataHelper(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
		_context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		executeDB(db, DBFILE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		android.util.Log.i("MoneyDataHelper", "DB Upgrade...");
		//It should be backed up before re-create new db
		//but at this time, I just create new one without backup
		onCreate(db);
	}
	
	/*
	 * read creating statements from asset file a execute them
	 * */
	private void executeDB(SQLiteDatabase db, String fileName){
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buf = new byte[1024];
		int len;
		AssetManager assetMgr = _context.getAssets();
		InputStream inputStream = null;
		
		try{
			inputStream = assetMgr.open(fileName);
			while( (len=inputStream.read(buf)) != -1 ){
				outStream.write(buf, 0, len);
			}
			outStream.close();
			inputStream.close();
			
			String[] creatingScript = outStream.toString().split(";");
			for(int i=0;i<creatingScript.length;i++){
				String createStatement = creatingScript[i] + ";";
				db.execSQL(createStatement);
			}
			
		}catch(IOException e1){
			android.util.Log.e("MoneyDataHelper", e1.getMessage());
		}catch(SQLException e2){
			android.util.Log.e("MoneyDataHelper", e2.getMessage());
		}
	}
}

